package com.ehualu.getes.until;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ParsedValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 吴敬超
 * @Date: 2019/11/19 11:15
 */
public class ESlluntil {


    public List<String[]> getliul(String starttime, String endTimeStr, String index, String[] kkid, RestHighLevelClient client) {

        List<String[]> list = new ArrayList<>();

        List<String> flaglist = new ArrayList<>();

        String indexName = index;

        try {

            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//			sourceBuilder.from(0); // 默认0
            sourceBuilder.size(10000);// 默认10条

            QueryBuilder queryBuilder;
            if (kkid[1] == null) {

                queryBuilder = QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("caddresscode.keyword", kkid[0]))
                        .must(QueryBuilders.rangeQuery("createtime").from(starttime).to(endTimeStr));
            } else {


                queryBuilder = QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("caddresscode.keyword", kkid))
                        .must(QueryBuilders.rangeQuery("createtime").from(starttime).to(endTimeStr));

            }


//            queryBuilder = QueryBuilders.termQuery()

//            根据时间升序排序
            sourceBuilder.sort("createtime", SortOrder.ASC);
            sourceBuilder.query(queryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response = client.search(searchRequest);

            Long rtlh = response.getHits().getTotalHits();
            System.out.println("查询数据量：" + rtlh);
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            int sl = searchHits.length;
            System.out.println("查询显示数据量：" + sl);
            for (SearchHit hit : searchHits) {

                String gcinfo[] = new String[4];

                Map<String, Object> sourceAsMap = hit.getSourceAsMap();// 获取查询结果json

                String strccarnumber = (String) sourceAsMap.get("ccarnumber");

                String gcsj = (String) sourceAsMap.get("createtime");
                String jd = (String) sourceAsMap.get("jd");
                String wd = (String) sourceAsMap.get("wd");


//                System.out.println("ccarnumber:" + strccarnumber);
//                System.out.println("createtime:" + gcsj);
                gcinfo[0] = strccarnumber;
                gcinfo[1] = gcsj;
                gcinfo[2] = jd;
                gcinfo[3] = wd;


                if (flaglist.contains(strccarnumber)) {

                    System.out.println("该车牌已经记录过了");
                } else {

//                    System.out.println("该车牌尚未记录");

                    flaglist.add(strccarnumber);

                    list.add(gcinfo);
                }

            }
            System.out.println("循环*****结束");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return list;
    }


    public String getliuluntilfordl(String index, String startime, String endtime, String fx, String[] dldmsz, RestHighLevelClient client) {

        String reshstart = startime;
        String reshend = endtime;

        System.out.println("********startime*********" + reshstart);
        System.out.println("********endtime*********" + reshend);

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = null;
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("createtime").from(reshstart).to(reshend));

        if (dldmsz.length == 1) {

            System.out.println("道路代码只有一个");
            boolQueryBuilder.must(QueryBuilders.termQuery("dldm.keyword", dldmsz[0]));

        } else if (dldmsz.length > 1) {

            boolQueryBuilder.must(QueryBuilders.termsQuery("dldm.keyword", dldmsz));

        } else {

            System.out.println("道路代码无");
            return "0";
        }

        if (fx.equals("nofx")) {
            System.out.println("没有方向条件");

        } else {

            boolQueryBuilder.must(QueryBuilders.termQuery("xsfx.keyword", fx));

        }

        queryBuilder = boolQueryBuilder;

        TermsAggregationBuilder field = AggregationBuilders.terms("terms_caddresscode").field("caddresscode.keyword");
        ValueCountAggregationBuilder countField = AggregationBuilders.count("count_caddresscode").field("caddresscode.keyword");

        field.subAggregation(countField);
        field.size(Integer.MAX_VALUE);
        sourceBuilder.aggregation(field);

        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }


        ParsedStringTerms termsName = response.getAggregations().get("terms_caddresscode");
        List<? extends Terms.Bucket> buckets = termsName.getBuckets();


        Integer bksize = buckets.size();
        System.out.println("根据卡口分组，分组数：" + bksize);


        if (bksize == 0) {

            System.out.println("卡口分组无结果");
            return "0";

        }

        double ct = 0.0;


        for (int i = 0; i < buckets.size(); i++) {


            String forkey = (String) buckets.get(i).getKey();
            System.out.println(forkey);
            ParsedValueCount countName = buckets.get(i).getAggregations().get("count_caddresscode");
            double value = countName.value();
            System.out.println(value);

            ct = ct + value;
        }

        Double avg = ct / bksize;

        System.out.println("平均数：" + avg);

        return avg.toString();

    }


    /*
     *危化品统计函数
     * */
    public String getliuluntilforwhp(String index, String startime, String endtime, String fx, String[] dldmsz, String[] whpcpsz, RestHighLevelClient client) {

        String reshstart = startime;
        String reshend = endtime;

        System.out.println("********startime*********" + reshstart);
        System.out.println("********endtime*********" + reshend);

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = null;
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("createtime").from(reshstart).to(reshend));

        if (dldmsz.length == 1) {

            System.out.println("道路代码只有一个");
            boolQueryBuilder.must(QueryBuilders.termQuery("dldm.keyword", dldmsz[0]));

        } else if (dldmsz.length > 1) {

            boolQueryBuilder.must(QueryBuilders.termsQuery("dldm.keyword", dldmsz));

        } else {

            System.out.println("道路代码无");
            return "0";
        }

        if (fx.equals("nofx")) {
            System.out.println("没有方向条件");

        } else {

            boolQueryBuilder.must(QueryBuilders.termQuery("xsfx.keyword", fx));

        }


        boolQueryBuilder.must(QueryBuilders.termsQuery("ccarnumber.keyword", whpcpsz));


        queryBuilder = boolQueryBuilder;

        TermsAggregationBuilder field = AggregationBuilders.terms("terms_caddresscode").field("caddresscode.keyword");
        ValueCountAggregationBuilder countField = AggregationBuilders.count("count_caddresscode").field("caddresscode.keyword");

        field.subAggregation(countField);
        field.size(Integer.MAX_VALUE);
        sourceBuilder.aggregation(field);

        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }


        ParsedStringTerms termsName = response.getAggregations().get("terms_caddresscode");
        List<? extends Terms.Bucket> buckets = termsName.getBuckets();


        Integer bksize = buckets.size();
        System.out.println("根据卡口分组，分组数：" + bksize);


        if (bksize == 0) {

            System.out.println("卡口分组无结果");
            return "0";

        }

        double ct = 0.0;


        for (int i = 0; i < buckets.size(); i++) {


            String forkey = (String) buckets.get(i).getKey();
            System.out.println(forkey);
            ParsedValueCount countName = buckets.get(i).getAggregations().get("count_caddresscode");
            double value = countName.value();
            System.out.println(value);

            ct = ct + value;
        }

        Double avg = ct / bksize;

        System.out.println("平均数：" + avg);

        return avg.toString();

    }


    /*
     *危化品统计函数修改细分
     * */
    public Double getliuluntilforwhpxf(String index, String startime, String endtime, String fx, String[] dldmsz, String[] whpcpsz, String[] hplxsz, RestHighLevelClient client) {

        String reshstart = startime;
        String reshend = endtime;

        System.out.println("********startime*********" + reshstart);
        System.out.println("********endtime*********" + reshend);

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = null;
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("createtime").from(reshstart).to(reshend));

        if (dldmsz.length == 1) {

            System.out.println("道路代码只有一个");
            boolQueryBuilder.must(QueryBuilders.termQuery("dldm.keyword", dldmsz[0]));

        } else if (dldmsz.length > 1) {

            boolQueryBuilder.must(QueryBuilders.termsQuery("dldm.keyword", dldmsz));

        } else {

            System.out.println("道路代码无");
            return 0.0;
        }

        if (fx.equals("nofx")) {
            System.out.println("没有方向条件");

        } else {

            boolQueryBuilder.must(QueryBuilders.termQuery("xsfx.keyword", fx));

        }
        if (hplxsz.length == 1) {

            boolQueryBuilder.must(QueryBuilders.termQuery("clicensetype.keyword", hplxsz[0]));


        } else {

            boolQueryBuilder.must(QueryBuilders.termsQuery("clicensetype.keyword", hplxsz));


        }


        boolQueryBuilder.must(QueryBuilders.termsQuery("ccarnumber.keyword", whpcpsz));


        queryBuilder = boolQueryBuilder;

        TermsAggregationBuilder field = AggregationBuilders.terms("terms_caddresscode").field("caddresscode.keyword");
        ValueCountAggregationBuilder countField = AggregationBuilders.count("count_caddresscode").field("caddresscode.keyword");

        field.subAggregation(countField);
        field.size(Integer.MAX_VALUE);
        sourceBuilder.aggregation(field);

        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }


        ParsedStringTerms termsName = response.getAggregations().get("terms_caddresscode");
        List<? extends Terms.Bucket> buckets = termsName.getBuckets();


        Integer bksize = buckets.size();
        System.out.println("根据卡口分组，分组数：" + bksize);


        if (bksize == 0) {

            System.out.println("卡口分组无结果");
            return 0.0;

        }

        double ct = 0.0;


        for (int i = 0; i < buckets.size(); i++) {


            String forkey = (String) buckets.get(i).getKey();
            System.out.println(forkey);
            ParsedValueCount countName = buckets.get(i).getAggregations().get("count_caddresscode");
            double value = countName.value();
            System.out.println(value);

            ct = ct + value;
        }

        Double avg = ct / bksize;

        System.out.println("平均数：" + avg);

        return avg;

    }


}
